package com.chenxin.quartz.task.mes;

import com.chenxin.common.utils.ConvertUtils;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.domain.wmsToMes.WmsToMesOrder;
import com.chenxin.interact.domain.mesNotice.OrderDetail;
import com.chenxin.interact.domain.mesNotice.OrderNoticeDTO;
import com.chenxin.interact.handler.mesHandler.MesOrderHandler;
import com.chenxin.interact.service.IUrlMapService;
import com.chenxin.interact.service.IWmsToMesOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component("orderNoticeTask")
public class OrderNoticeTask {
    @Autowired
    private IUrlMapService urlMapService;
    @Autowired
    private MesOrderHandler orderHandler;
    @Autowired
    private IWmsToMesOrderService wmsToMesOrderService;

    public void run(String method) {
        // 获取所有启用的接口
        UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("MES_POST_URL");
        if (urlMap == null) {
            log.error("接口【MES_POST_URL】未定义!");
            return;
        }
        // 获取需上报的订单
        List<WmsToMesOrder> orders = wmsToMesOrderService.selectWmsToMesOrderList();
        if (orders == null || orders.size() == 0) {
            log.info("无待上报的出库订单!");
            return;
        }
        // 统计需上报的订单号
        List<String> stockNos = orders.stream().map(WmsToMesOrder::getStockNo)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());

        for (String stockNo : stockNos) {
            List<WmsToMesOrder> ordersByStockNo = orders.stream().filter(order -> order.getStockNo().equals(stockNo))
                    .collect(Collectors.toList());
            //List<OrderDetail> details = ConvertUtils.sourceToTarget(ordersByStockNo, OrderDetail.class);
            List<OrderDetail> details = new ArrayList<>();
            for (WmsToMesOrder order : ordersByStockNo) {
                OrderDetail orderDetail = ConvertUtils.sourceToTarget(order, OrderDetail.class);
                orderDetail.setSendOperatorId("SysAdmin");
                orderDetail.setSendDate(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                details.add(orderDetail);
            }

            OrderNoticeDTO noticeDTO = new OrderNoticeDTO();
            noticeDTO.setStockNo(stockNo);
            noticeDTO.setDetail(details);
            // 调用接口上报MES
            try {
                orderHandler.notice(urlMap, noticeDTO, method);
            } catch (Exception e) {
                log.error("订单【{}】上报MES异常!", stockNo, e);
            }
        }
    }
}
